import { BattleReport, TurnResult, BattleAction, Team } from '../types/battle';
import { General } from '../models/General';

export class BattleReporter {
  private report: BattleReport;

  constructor() {
    this.report = {
      turns: [],
      finalState: {
        remainingTroops: new Map(),
        totalDamage: new Map(),
        totalHealing: new Map()
      }
    };
  }

  public recordTurn(turnResult: TurnResult, turnNumber: number): void {
    this.report.turns.push({
      ...turnResult,
      turnNumber,
      timestamp: Date.now()
    });

    // Update statistics
    this.updateStatistics(turnResult.actions);
  }

  public setWinner(winner: Team): void {
    this.report.winner = winner;
  }

  public recordFinalState(teams: Team[]): void {
    teams.forEach(team => {
      team.generals.forEach(general => {
        this.report.finalState.remainingTroops.set(general.id, general.troops);
      });
    });
  }

  public getReport(): BattleReport {
    return this.report;
  }

  private updateStatistics(actions: BattleAction[]): void {
    actions.forEach(action => {
      if (action.type === 'attack' || action.type === 'skill') {
        // Update damage statistics
        const currentDamage = this.report.finalState.totalDamage.get(action.actor.id) || 0;
        this.report.finalState.totalDamage.set(action.actor.id, currentDamage + action.damage);

        // Update healing statistics if applicable
        if (action.healing) {
          const currentHealing = this.report.finalState.totalHealing.get(action.actor.id) || 0;
          this.report.finalState.totalHealing.set(action.actor.id, currentHealing + action.healing);
        }
      }
    });
  }

  public generateBattleSummary(): string {
    let summary = `Battle Summary\n`;
    summary += `Total Turns: ${this.report.turns.length}\n`;
    summary += `Winner: ${this.report.winner ? this.report.winner.id : 'Draw'}\n\n`;

    // Add damage and healing statistics
    summary += `Damage Dealt:\n`;
    this.report.finalState.totalDamage.forEach((damage, generalId) => {
      summary += `${generalId}: ${damage}\n`;
    });

    return summary;
  }
}
